<template>
  <div class="rollchange-page">
    <div class="filter-bar">
      <el-form :inline="true" :model="filters" class="filter-form">

        <el-form-item>
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-tabs v-model="activeTab" class="roll-tabs" style="margin-bottom: 16px;">
        <el-tab-pane label="1630连退" name="LB2" />
        <el-tab-pane label="2150连退" name="LB1" />
        <el-tab-pane label="酸轧" name="A1" />
    </el-tabs>
    <el-table :data="tableData" class="roll-table" height="calc(100vh - 180px)" empty-text="暂无数据" border>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column label="上辊信息" align="center">
        <el-table-column prop="rollerNO" label="辊号" width="120" align="center" />
        <el-table-column prop="realDia" label="直径[mm]" width="140" align="center" />
        <el-table-column prop="crownTm" label="凸度" width="110" align="center" />
      </el-table-column>
            <el-table-column label="下辊信息" align="center">
        <el-table-column prop="rollerNO1" label="辊号" width="120" align="center" />
        <el-table-column prop="realDia1" label="直径[mm]" width="140" align="center" />
        <el-table-column prop="crownTm" label="凸度" width="110" align="center" />
      </el-table-column>

      <el-table-column prop="loadTime" label="上线时间" align="center" :formatter="formatDate"/>
      <el-table-column prop="endTime" label="下线时间" align="center" :formatter="formatDate"/>
      <el-table-column prop="standNO" label="机架" align="center" >
        <template #default="scope">
          <span>{{ scope.row.standNO=='A'?'酸轧轧机1#机架':scope.row.standNO=='B'?'酸轧轧机2#机架':scope.row.standNO=='C'?'酸轧轧机3#机架':scope.row.standNO=='D'?'酸轧轧机4#机架':scope.row.standNO=='E'?'酸轧轧机5#机架':scope.row.standNO=='F'?'连退2150平整机':scope.row.standNO=='G'?'连退1630平整机':'镀锌1870光整机' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="areaCode" label="位置" align="center">
        <template #default="scope">
          <span>{{ scope.row.areaCode=='A1'?'酸轧':scope.row.areaCode=='LB1'?'连退1#':scope.row.areaCode=='LB2'?'连退2#':'镀锌' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="rollWorkingWt" label="轧制重量[t]" align="center">
        <template #default="scope">
          {{Math.floor(scope.row.rollWorkingWt/1000)}}
        </template>
      </el-table-column>
      <el-table-column prop="rollWorkingLen" label="轧制长度[m]" align="center" />
    </el-table>

     <!-- 分页区域 -->
    <div class="pagination-panel">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { acidRollingApi } from '/@/api/acidRollingProductionEfficiency/index';
import dayjs from 'dayjs'

const route = useRoute();

const filters = ref({
  team: 'all',
  dateRange: [] as string[]
})

const activeTab = ref('LB2'); // 默认1630连退

const tableData = ref([])

// --- Pagination --- 
const pagination = reactive({
  currentPage: 1,
  pageSize: 50,
  total: tableData.value.length
});

onMounted(() => {
  // 检查是否有路由参数
  const rollerNO = route.query.rollerNO as string;
  
  if (rollerNO) {
    // 如果有辊号参数，自动填充搜索表单并查询
    // 这里可以根据需要添加辊号搜索字段
    console.log('接收到辊号参数:', rollerNO);
    // 直接查询该辊号的数据
    fetchTableDataWithRollerNO(rollerNO);
  } else {
    // 没有参数时正常加载数据
    fetchTableData();
  }
});
function formatDate(row: any, column: any, cellValue: any) {
  if (!cellValue) return '';
  return dayjs(cellValue).format('YYYY-MM-DD HH:MM:ss');
}

function onTabChange() {
  console.log(activeTab.value)
  tableData.value = [];
  pagination.currentPage = 1;
  fetchTableData();
}

// 根据辊号获取表格数据
const fetchTableDataWithRollerNO = async (rollerNO: string) => {
  try {
    const params: any = {
      pageIndex: String(pagination.currentPage),
      pageSize: String(pagination.pageSize),
      rollerNO: rollerNO, // 添加辊号参数
      areaCode: activeTab.value, // 新增
    };

    // 移除未定义的参数，避免发送空字符串
    Object.keys(params).forEach(key => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    console.log("Fetching data with rollerNO params:", params);
    const response = await acidRollingApi.getRollChange(params);
    console.log("API Response:", response);

    // Correctly access data from response.data if 'response' is an AxiosResponse
    const responseData = response.data;

    if (
      responseData &&
      responseData.data &&
      Array.isArray(responseData.data)
    ) {
      tableData.value = responseData.data.map((item: any) => ({
        ...item
      }));
      console.log(tableData.value);
      pagination.total = responseData.count || responseData.data.length; // Use responseData.count for total
      ElMessage.success(`查询辊号 ${rollerNO} 的数据成功`);
    } else {
      ElMessage.info(
        responseData?.msg ||
          (response as any)?.msg ||
          "未查询到数据或响应格式不正确"
      );
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    console.error("获取数据失败:", error);
    // Try to get error message from error.response.data.msg or error.data.msg
    const errorMessage =
      error.response?.data?.msg ||
      error.data?.msg ||
      error.msg ||
      error.message ||
      "获取数据失败";
    ElMessage.error(errorMessage);
    tableData.value = [];
    pagination.total = 0;
  }
};

// 获取表格数据
const fetchTableData = async () => {
  try {
    const params: any = {
      pageIndex: String(pagination.currentPage),
      pageSize: String(pagination.pageSize),
      startDate:filters.value.dateRange[0],
      endDate:filters.value.dateRange[1],
      areaCode: activeTab.value, // 新增
    };

    // 移除未定义的参数，避免发送空字符串
    Object.keys(params).forEach(key => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    console.log("Fetching data with params:", params);
    const response = await acidRollingApi.getRollChange(params);
    console.log("API Response:", response);

    // Correctly access data from response.data if 'response' is an AxiosResponse
    const responseData = response.data;

    if (
      responseData &&
      responseData.data &&
      Array.isArray(responseData.data)
    ) {
      tableData.value = responseData.data.map((item: any) => ({
        ...item
      }));
      console.log(tableData.value);
      pagination.total = responseData.count || responseData.data.length; // Use responseData.count for total
      ElMessage.success(responseData.msg || "查询成功");
    } else {
      ElMessage.info(
        responseData?.msg ||
          (response as any)?.msg ||
          "未查询到数据或响应格式不正确"
      );
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    console.error("获取数据失败:", error);
    // Try to get error message from error.response.data.msg or error.data.msg
    const errorMessage =
      error.response?.data?.msg ||
      error.data?.msg ||
      error.msg ||
      error.message ||
      "获取数据失败";
    ElMessage.error(errorMessage);
    tableData.value = [];
    pagination.total = 0;
  }
};
watch(activeTab, (newVal) => {
  tableData.value = [];
  pagination.currentPage = 1;
  fetchTableData();
});

function onSearch() {
  // 查询逻辑
  pagination.currentPage = 1;
  fetchTableData();
}
function onReset() {
  filters.value = { team: 'all', dateRange: [] }
}

// 页码变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchTableData();
};
// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchTableData();
};
</script>

<style scoped>
.rollchange-page {
  background: url('../../assets/images/body-bg.jpg') no-repeat center center;
  min-height: 100vh;
  padding: 24px 18px 18px 18px;
  
}
.filter-bar {
  margin-bottom: 18px;
}
.filter-form {
  background: transparent;
}

:deep(.el-table),
:deep(.el-table__body),
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__empty-block) {
  background: linear-gradient(135deg, #183c7e 0%, #0a1a3a 100%) !important;
}
:deep(.el-table th),
:deep(.el-table td) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__body tr) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__body tr:hover > td) {
  background-color: #223a6b !important;
}

/* --- Pagination Panel (Styles should be consistent) --- */
.pagination-panel {
  background-color: #1c2d5a;
  padding: 8px 15px;
  border-radius: 3px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}
:deep(.el-pagination) {
  background-color: transparent !important;
}
:deep(.el-pagination__total),
:deep(.el-pagination__sizes),
:deep(.el-pagination__jump),
:deep(.el-pagination__editor),
:deep(.el-pagination button),
:deep(.el-pager li) {
  background-color: #1c2d5a !important;
  color: #7ec7ff !important;
  border: none !important;
}
:deep(.el-pager li.is-active) {
  background-color: #2979ff !important;
  color: #fff !important;
}

.single-roll-analysis>*:not(:last-child) {
  margin-bottom: 15px;
}

:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__border-left-patch),
:deep(.el-table--border .el-table__inner-wrapper::before) {
  z-index: -1;
}


:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #06279d !important;
}
:deep(.el-table--border td.el-table__cell),
:deep(.el-table--border th.el-table__cell) {
  border-right: 1px solid #06279d !important;
  border-bottom:none;
}
:deep(.el-table thead){
  color:#fff !important
}

:deep(.el-table){
  color:#fff !important
}

:deep(.el-tabs__item){
  color:#fff
}

</style>
